from django.db import models
from pygments.lexers import get_all_lexers, get_lexer_by_name
from pygments.styles import get_all_styles

from pygments.formatters import HtmlFormatter
from pygments import highlight


# Create your models here.
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item,item) for item in get_all_styles()])


class Snippet(models.Model):
    created = models.DateTimeField('创建时间', auto_now_add=True)
    title = models.CharField('标题', max_length=100, blank=True, default='')
    code = models.TextField('代码')
    linenos = models.BooleanField('是否添加行号', default=False)
    language = models.CharField('代码语言', choices=LANGUAGE_CHOICES, default='Python', max_length=100)
    style = models.CharField('代码风格', choices=STYLE_CHOICES, default = 'friendly', max_length=100)
    owner = models.ForeignKey('auth.User',related_name='snippets', on_delete=models.CASCADE)
    highlighted = models.TextField()

    def save(self, *args, **kwargs):
        """使用pygments库创建突出显式的Html代码段"""
        lexer = get_lexer_by_name(self.language)
        linenos = 'table' if self.linenos else False
        options = {'title': self.title} if self.title else {}
        formatter = HtmlFormatter(styles=self.style, linenos=linenos, full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super().save(*args, **kwargs)

    class Meta:
        ordering = ['created']